<?php

/**
 *    前台控制器基础类
 *
 *    @author    Garbin
 *    @usage    none
 */
class FrontendApp extends ECBaseApp
{

    var $ver_info = '1.1.5';

    function __construct()
    {
        $this->FrontendApp();
    }

    function FrontendApp()
    {
        Lang::load(lang_file('common'));
        Lang::load(lang_file(APP));
        parent::__construct();

        // 判断商城是否关闭
        if (!Conf::get('site_status'))
        {
            $this->show_warning(Conf::get('closed_reason'));
            exit;
        }
        # 在运行action之前，无法访问到visitor对象
    }

    function _config_view()
    {
        parent::_config_view();
        $this->_view->template_dir = ROOT_PATH . '/themes';
        $this->_view->compile_dir = ROOT_PATH . '/temp/compiled/mall';
        $this->_view->res_base = SITE_URL . '/themes';
        $this->_config_seo(array(
            'title' => Conf::get('site_title'),
            'description' => Conf::get('site_description'),
            'keywords' => Conf::get('site_keywords')
        ));
    }
    
    function _in_display()
    {
        $cart_mod = & m('cart');
        $this->assign('cart_goods_kinds', $cart_mod->get_kinds(SESS_ID, $this->visitor->get('user_id')));
        $this->assign('new_message', isset($this->visitor) ? $this->_get_new_message() : ''); //新消息
        $this->assign('hot_keywords', $this->_get_hot_keywords()); //热门搜素
        $this->assign('navs', $this->_get_navs());  // 自定义导航
        $this->assign('shop_help', $this->_get_shop_help());  // 帮助中心文章
        $this->assign('nav_gcategory', $this->_get_nav_gcategory());  // 导航商品分类
        $this->assign('nav_placecategory', $this->_get_nav_placecategory());  // 导航场景分类
        $this->assign('links_list', $this->_get_links_list());  // 友情链接
        $this->assign('cart_top_list', $cart_mod->get_cart_top(SESS_ID, $this->visitor->get('user_id')));   // 购物车前面的前5条数据
        $this->assign('acc_help', ACC_HELP);        // 帮助中心分类code
        $this->assign('site_title', Conf::get('site_title'));
        $this->assign('site_logo', Conf::get('site_logo'));
        $this->assign('statistics_code', Conf::get('statistics_code')); // 统计代码
        $this->assign('rewrite_enabled', Conf::get('rewrite_enabled'));
        $this->assign('ver_info', $this->ver_info);
        $this->assign('res_dir', $this->_get_res_name());
        $current_url = explode('/', $_SERVER['REQUEST_URI']);
        $count = count($current_url);
        $current_url_str = $count > 1 ? $current_url[$count - 1] : $_SERVER['REQUEST_URI'];
        if (strpos($current_url_str, 'app=search&is_hot=1'))
        {
            $current_url_str = 'search/is_hot.html';
        }
        $this->assign('current_url', $current_url_str); // 用于设置导航状态(以后可能会有问题)
    }

    function display($tpl)
    {
        $this->_in_display();
        parent::display($tpl);
    }
    
    function return_display($tpl)
    {
        $this->_in_display();
        return parent::return_display($tpl);
    }
    
    //用户登录
    function login()
    {
        //直接token登陆
        $token = (isset($_GET['token']) && $_GET['token']) ? $_GET['token'] : '';
        if (!empty($token))
        {
            include_once ROOT_PATH . "/includes/string.php";
            $user_info = String::authCode(base64_decode($token), 'DECODE', 'wljiashi');
            $infoArr = explode('|', $user_info);
            if (count($infoArr) == 3)
            {
                $user_id = $infoArr[0];
                if(isset($_SESSION['user_token_id']) && $_SESSION['user_token_id'] != $user_id){
                    $this->show_warning("你已经登陆了一个卖家，如再登陆其他卖家，请先把之前登陆的卖家登出！", '登出', 'index.php?app=member&act=logout');
                    return;
                }
                $_SESSION['user_token_id'] = $user_id;
                $this->_do_login($user_id);
                header("Location:index.php?app=seller");
                return;
            }else{
                $this->show_warning("参数错误!!!");
                return;
            }
        }
        //正常情况
        if ($this->visitor->has_login)
        {
            header("Location:index.php?app=member");
            return;
        }
        if (!IS_POST)
        {
            if (!empty($_GET['ret_url']))
            {
                $ret_url = trim($_GET['ret_url']);
            }
            else
            {
                if (isset($_SERVER['HTTP_REFERER']))
                {
                    $ret_url = $_SERVER['HTTP_REFERER'];
                }
                else
                {
                    $ret_url = SITE_URL . '/index.php';
                }
            }
            /* 防止登陆成功后跳转到登陆、退出的页面 */
            $ret_url = strtolower($ret_url);
            if (str_replace(array('act=login', 'act=logout',), '', $ret_url) != $ret_url)
            {
                $ret_url = SITE_URL . '/index.php';
            }

            if (Conf::get('captcha_status.login'))
            {
                $this->assign('captcha', 1);
            }
            $this->import_resource(array('script' => 'jquery.plugins/jquery.validate.js,jquery.plugins/additional-methods.js'));
            $this->assign('ret_url', rawurlencode($ret_url));
            $this->_curlocal(LANG::get('user_login'));
            $this->_config_seo('title', Lang::get('user_login') . '-' . Lang::get('site_title'));
            $this->assign('app_img', 'logintt.jpg');
            $this->assign('user_name', $_COOKIE['remember_login_account']);
            $this->display('login.html');
            /* 同步退出外部系统 */
            if (!empty($_GET['synlogout']))
            {
                $ms = & ms();
                echo $synlogout = $ms->user->synlogout();
            }
        }
        else
        {
            if (Conf::get('captcha_status.login') && base64_decode($_SESSION['captcha']) != strtolower($_POST['captcha']))
            {
                $this->show_warning('captcha_failed');

                return;
            }

            $user_name = trim($_POST['user_name']);
            $password = $_POST['password'];
            $remember_account = $_POST['remember_account'];
            $ms = & ms();
            $user_id = $ms->user->auth($user_name, $password);
            if (!$user_id)
            {
                /* 未通过验证，提示错误信息 */
                $this->show_warning($ms->user->get_error());

                return;
            }
            else
            {
                /* 通过验证，执行登陆操作 */
                $this->_do_login($user_id);

                /* 同步登陆外部系统 */
                $synlogin = $ms->user->synlogin($user_id);
            }
            //记住账号
            if (isset($remember_account) && $remember_account == 1)
            {
                ecm_setcookie('remember_login_account', $user_name, time() + 36000);
            }

            $this->show_message(Lang::get('login_successed') . $synlogin, 'back_before_login', rawurldecode($_POST['ret_url']), 'enter_member_center', 'index.php?app=member'
            );
        }
    }

    //用户AJAX登录
    function Ajaxlogin()
    {
        if ($this->visitor->has_login)
        {
            $this->json_error('has_login');
            return;
        }
        $user_name = trim(addslashes($_REQUEST['user_name']));
        $password = trim(addslashes($_REQUEST['password']));
        $remember_account = intval(addslashes($_REQUEST['remember_account']));
        if (Conf::get('captcha_status.login') && base64_decode($_SESSION['captcha']) != strtolower($_POST['captcha']))
        {
            $this->json_error('captcha_failed');
            return;
        }
        if ((!$user_name && !is_account($user_name)) || !$password)
        {
            $this->json_error('用户名或者密码错误');
            return;
        }

        $ms = & ms();
        $user_id = $ms->user->auth($user_name, $password);
        if (!$user_id)
        {
            /* 未通过验证，提示错误信息 */
            $this->json_error('用户名或者密码错误');
            return;
        }
        else
        {
            /* 通过验证，执行登陆操作 */
            $this->_do_login($user_id);

            /* 同步登陆外部系统 */
            $synlogin = $ms->user->synlogin($user_id);
        }
        //记住账号
        if (isset($remember_account) && $remember_account == 1)
        {
            ecm_setcookie('remember_login_account', $user_name, time() + 36000);
        }

        $this->json_result('', 'login_successed');
        return;
    }

    //用户是否登录
    function Ajax_islogin()
    {
        if ($this->visitor->has_login)
        {
            $user_id = $this->visitor->get('user_id');
            $user_name = $this->visitor->get('user_name');
            $user_portrait = $this->visitor->get('portrait');
            if (!$user_portrait || !file_exists($user_portrait))
            {
                $user_portrait = SITE_URL . '/data/system/default_user_portrait.gif';
            }
            /* 买家提醒：待付款、待收货、待评价订单数 */
            $order_mod = & m('order');
            $sql = "SELECT 
                    count(case when status = '" . ORDER_PENDING . "' then order_id end) submitted,
                    count(case when status = '" . ORDER_SHIPPED . "' then order_id end) shipped,
                    count(case when status = '" . ORDER_FINISHED . "' AND evaluation_status = 0 then order_id end) evalua
                    FROM {$order_mod->table} where buyer_id = '{$user_id}'";
            $user_data = $order_mod->getRow($sql);
            $user_data['user_id'] = $user_id;
            $user_data['user_name'] = $user_name;
            $user_data['user_portrait'] = $user_portrait;
            $this->json_result($user_data, 'has_login');
            return;
        }
        else
        {
            $this->json_error('login_please');
            return;
        }
    }

    function pop_warning($msg, $dialog_id = '', $url = '')
    {
        if ($msg == 'ok')
        {
            if (empty($dialog_id))
            {
                $dialog_id = APP . '_' . ACT;
            }
            if (!empty($url))
            {
                echo "<script type='text/javascript'>window.location.href='" . $url . "';</script>";
            }

            echo "<script type='text/javascript'>window.parent.js_success('" . $dialog_id . "');</script>";
        }
        else
        {
            header("Content-Type:text/html;charset=" . CHARSET);
            $msg = is_array($msg) ? $msg : array(array('msg' => $msg));
            $errors = '';
            foreach ($msg as $k => $v)
            {
                $error = $v[obj] ? Lang::get($v[msg]) . " [" . Lang::get($v[obj]) . "]" : Lang::get($v[msg]);
                $errors .= $errors ? "<br />" . $error : $error;
            }
            echo "<script type='text/javascript'>window.parent.js_fail('" . $errors . "');</script>";
        }
    }

    function logout()
    {
        $this->visitor->logout();
        unset($_SESSION['user_token_id']);
        /* 跳转到登录页，执行同步退出操作 */
        header("Location: index.php?app=member&act=login&synlogout=1");
        return;
    }

    /* 执行登录动作 */

    function _do_login($user_id)
    {
        $mod_user = & m('member');

        $user_info = $mod_user->get(array(
            'conditions' => "user_id = '{$user_id}'",
            'join' => 'has_store', //关联查找看看是否有店铺
            'fields' => 'user_id, user_name, reg_time, last_login, last_ip, store_id, sgrade',
        ));

        /* 店铺ID */
        $my_store = empty($user_info['store_id']) ? 0 : $user_info['store_id'];

        /* 保证基础数据整洁 */
        //unset($user_info['store_id']);

        /* 分派身份 */
        $this->visitor->assign($user_info);

        /* 更新用户登录信息 */
        $mod_user->edit("user_id = '{$user_id}'", "last_login = '" . gmtime() . "', last_ip = '" . real_ip() . "', logins = logins + 1");

        /* 更新购物车中的数据 */
        $mod_cart = & m('cart');
        $mod_cart->edit("(user_id = '{$user_id}' OR session_id = '" . SESS_ID . "') AND store_id <> '{$my_store}'", array(
            'user_id' => $user_id,
            'session_id' => SESS_ID,
        ));

        /* 重复的时候合并购物车 */
        $cart_items = $mod_cart->find(array(
            'conditions' => "user_id='{$user_id}' GROUP BY spec_id",
            'fields' => 'COUNT(spec_id) as spec_count, SUM(quantity) as sum_quantity, spec_id, rec_id, goods_id',
        ));
        if (!empty($cart_items))
        {
            $goods_ids = array();
            foreach ($cart_items as $rec_id => $cart_item)
            {
                if ($cart_item['spec_count'] > 1)
                {
                    $goods_ids[] = $cart_item['goods_id'];
                    $mod_cart->edit("user_id='{$user_id}' AND rec_id='{$cart_item['rec_id']}'", array('quantity' => $cart_item['sum_quantity']));
                    $mod_cart->drop("user_id='{$user_id}' AND spec_id='{$cart_item['spec_id']}' AND rec_id <> {$cart_item['rec_id']}");
                }
            }
            if ($goods_ids)
            {
                array_unique($goods_ids);
                $mod_goods = & m('goods');
                $activity_goods_model =& m('activitygoods');
                foreach ($goods_ids as $key => $goods_id)
                {
                    $goods_price_type = $mod_goods->get_fields_name($goods_id, 'price_type');
                    if ($goods_price_type == 1)
                    {
                        $cart_totalnum = $mod_cart->get_goods_totalnum(SESS_ID, $goods_id); //购物车包含商品的总数量
                        $retail_price = $mod_cart->get_volume_price($goods_id, $cart_totalnum); //获取价格区间的价格
                        $activity  = $activity_goods_model->_get_activity_goods($goods_id);//获取商品参与活动的数据
                        $activity_goods = current($activity);
                        if($activity_goods['discount_type'] == 1)
                        {
                            $price = $retail_price*$activity_goods['promote_discount'];
                        }
                        if($activity_goods['discount_type'] == 2)
                        {
                            $price = $activity_goods['promote_price'];
                        }
                        $goods_price = floatval($price) > 0 ? $price : $retail_price;
                        /* 更新适合条件商品的价格 */
                        $mod_cart->edit_cart_price($retail_price, $goods_price, " session_id='" . SESS_ID . "' AND goods_id = {$goods_id}");
                    }
                }
            }
        }
    }

    /* 取得导航 */

    function _get_navs()
    {
        $cache_server = & cache_server();
        $key = 'common.navigation';
        $data = $cache_server->get($key);
        if ($data === false)
        {
            $data = array(
                'header' => array(),
                'middle' => array(),
                'footer' => array(),
            );
            $nav_mod = & m('navigation');
            $rows = $nav_mod->find(array(
                'order' => 'type, sort_order',
            ));
            foreach ($rows as $row)
            {
                $data[$row['type']][] = $row;
            }
            $cache_server->set($key, $data, 86400);
        }

        return $data;
    }

    /**
     * 帮助中心信息
     *
     * @author    yanghi 2014.6.3
     * @return  array
     */
    function _get_shop_help()
    {
        $cacheServer = cache_server();
        $key = "frontendapp_get_shop_help";
        $data = $cacheServer->get($key);
        if ($data === false)
        {
        $article_mod = & m('article');
        $acategory_mod = & m('acategory');
        $cate_data = $acategory_mod->getAll("SELECT cate_id,cate_name FROM {$acategory_mod->table} WHERE parent_id = 1 order by sort_order asc  limit 3");
        if ($cate_data)
        {
            foreach ($cate_data as $k => $row)
            {
                $data[$row['cate_id']]['cate_id'] = $row['cate_id'];
                $data[$row['cate_id']]['cate_name'] = $row['cate_name'];
                $data[$row['cate_id']]['article'] = $article_mod->find(array(
                    'conditions' => "if_show = 1 AND store_id=0 AND cate_id = " . $row['cate_id'],
                    'fields' => 'title, cate_id, link',
                    'order' => 'sort_order asc, add_time desc',
                    'limit' => 4,
                ));
            }
        }
            $cacheServer->set($key, $data, 300);
        }
        return $data;
    }

    /**
     * 获取导航商品分类信息
     *
     * @author    yanghi 2014.6.24
     * @return  array
     */
    /*function _get_nav_gcategory()
    {
        $arr = array();
        $gcategory_mod = & m('gcategory');
        $res = $gcategory_mod->find(array(
            'conditions' => "type_id != 0 AND if_show = 1 ",
            'fields' => 'cate_id, cate_name, parent_id, type_id, short_name, is_recommend',
            'order' => 'type_id,sort_order,cate_id asc',
        ));
        $cate_ids = $gcategory_mod->getCol("SELECT cate_id FROM {$gcategory_mod->table} WHERE parent_id = 0 ");
        if (!$res)
        {
            return $arr;
        }
        foreach ($res as $val)
        {
            if ($val['is_recommend'] == 1)
            {
                $arr[$val['type_id']]['one'][$val['cate_id']]['cate_id'] = $val['cate_id'];
                $arr[$val['type_id']]['one'][$val['cate_id']]['cate_name'] = empty($val['short_name']) ? $val['cate_name'] : $val['short_name'];
            }
            if (in_array($val['parent_id'], $cate_ids))
            {
                $arr[$val['type_id']]['tow'][$val['cate_id']]['cate_id'] = $val['cate_id'];
                $arr[$val['type_id']]['tow'][$val['cate_id']]['cate_name'] = $val['cate_name'];
                $arr[$val['type_id']]['tow'][$val['cate_id']]['children'] = $gcategory_mod->get_list($val['cate_id'], true);
            }
        }
        return $arr;
    }*/

    /**
     * 获取导航商品分类信息
     *
     * @author    yanghi 2015.3.2
     * @return  array
     */
    function _get_nav_gcategory()
    {
        $gcategory_mod =& bm('gcategory', array('_store_id' => 0));
        $recommendstore_mod = & m('recommendstore');
        $hotgoods_mod = & m('hotgoods');
        $store_mod = & m('store');
        $goods_mod = & m('goods');
        $cacheServer = cache_server();
        $key = "frontendapp_get_nav_gcategory";
        $data = $cacheServer->get($key);
        $store_data = $recommendstore_mod->get_list();//获取分类关联的店铺
        $goods_category = $cacheServer->get('search_goods_category');//商品所有的分类
        $goods_category = false;
        if($goods_category === false)
        {
            $gcategories = $gcategory_mod->get_list(-1,true);
            import('tree.lib');
            $tree = new Tree();
            $tree->setTree($gcategories, 'cate_id', 'parent_id', 'cate_name');
            $goods_category = $tree->getArrayListWithId(0);
        }

        if ($data === false)
        {
            $cate_data = $gcategory_mod->getAll("SELECT cate_id,cate_name FROM {$gcategory_mod->table} WHERE parent_id = 0 AND  if_show = 1 AND store_id = 0 ORDER BY sort_order ASC ");
            //分类的数据
            foreach ($cate_data as $val)
            {
                $ids =  $gcategory_mod->get_descendant_ids($val['cate_id']);
                $recommend_gcategory = $gcategory_mod->find(array(
                    'conditions' => "is_recommend = 1 AND if_show = 1 AND cate_id ". db_create_in($ids),
                    'fields' => 'cate_id, cate_name, short_name',
                    'order' => 'sort_order,cate_id asc',
                    'limit' => '8',
                ));

                $data['gcategory'][$val['cate_id']]['cate_id'] = $val['cate_id'];
                $data['gcategory'][$val['cate_id']]['cate_name'] = $val['cate_name'];
                if ($recommend_gcategory)
                {
                    $data['gcategory'][$val['cate_id']]['one'] = $recommend_gcategory;
                }
                $data['gcategory'][$val['cate_id']]['tow'] = $goods_category[$val['cate_id']]['children'];
                if(!empty($store_data[$val['cate_id']]['store_text']))
                {
                    $recommend_store = $store_mod->find(array(
                        'conditions' => "state = 1 AND store_id IN(".$store_data[$val['cate_id']]['store_text'].")",
                        'fields' => 'store_id, store_name, store_logo',
                        'limit' => '6',
                    ));
                    if($recommend_store)
                    {
                        foreach($recommend_store as $store_id=>$store)
                        {
                            empty($store['store_logo']) && $recommend_store[$store_id]['store_logo'] = Conf::get('default_store_logo');
                        }
                        $data['gcategory'][$val['cate_id']]['three'] = $recommend_store;
                    }
                }

            }
            //本期热卖的数据
            $hot_goods = $hotgoods_mod->find(array(
                'fields' => 'title, link, is_recommend, is_hot',
                'order' => 'sort_order,id desc',
            ));
            if($hot_goods)
            {
                foreach($hot_goods as $k=>$val)
                {
                    if($val['is_recommend'] == 1)
                    {
                        $data['hot_goods']['one'][$k]['title'] = $val['title'];
                        $data['hot_goods']['one'][$k]['link'] = $val['link'];
                    }

                }
                $data['hot_goods']['tow'] = $hot_goods;

            }
            if(!empty($store_data[-1]['store_text']))
            {
                $recommend_goods = $goods_mod->find(array(
                    'conditions' => "if_show = 1 AND closed = 0 AND goods_id IN(".$store_data[-1]['store_text'].")",
                    'fields' => 'goods_id, goods_name, default_image, price',
                    'limit' => '6',
                ));
                $data['hot_goods']['three'] = $recommend_goods;
            }


            $cacheServer->set($key, $data, 86400);
        }
        return $data;
    }

    /*
     * 获取场景分类信息
     */

    function _get_nav_placecategory()
    {
        $cacheServer = cache_server();
        $key = "frontendapp_get_nav_placecategory";
        $data = $cacheServer->hGet("placecategory", $key);
        if ($data === false)
        {
            $placecategory_mod = m("placecategory");
            import('tree.lib');
            $tree = new Tree();
            $categories = $placecategory_mod->get_list(-1, true, true);
            $tree->setTree($categories, 'cate_id', 'parent_id', 'cate_name');
            $data = $tree->getArrayListWithId();
            $cacheServer->hSet($placecategory_mod->_name, $key, $data, $placecategory_mod->expire);
        }
        return $data;
    }

    /**
     * 获取友情链接
     *
     * @author  yanghi 2014.7.4
     * @return  array
     */
    function _get_links_list()
    {
        $partner_mod = & m('partner');
        $data = $partner_mod->find(array(
            'conditions' => "store_id = 0",
            'order' => 'sort_order',
        ));
        return $data;
    }

    /**
     *    获取JS语言项
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function jslang()
    {
        $lang = Lang::fetch(lang_file('jslang'));
        parent::jslang($lang);
    }

    /**
     *    视图回调函数[显示小挂件]
     *
     *    @author    Garbin
     *    @param     array $options
     *    @return    void
     */
    function display_widgets($options)
    {
        $area = isset($options['area']) ? $options['area'] : '';
        $page = isset($options['page']) ? $options['page'] : '';
        if (!$area || !$page)
        {
            return;
        }
        include_once(ROOT_PATH . '/includes/widget.base.php');

        /* 获取该页面的挂件配置信息 */
        $widgets = get_widget_config($this->_get_template_name(), $page);

        /* 如果没有该区域 */
        if (!isset($widgets['config'][$area]))
        {
            return;
        }

        /* 将该区域内的挂件依次显示出来 */
        foreach ($widgets['config'][$area] as $widget_id)
        {
            $widget_info = $widgets['widgets'][$widget_id];
            $wn = $widget_info['name'];
            $options = $widget_info['options'];

            $widget = & widget($widget_id, $wn, $options);
            $widget->display();
        }
    }

    /**
     *    获取当前使用的模板名称
     *
     *    @author    Garbin
     *    @return    string
     */
    function _get_template_name()
    {
        return 'default';
    }

    /**
     *    获取当前使用的风格名称
     *
     *    @author    Garbin
     *    @return    string
     */
    function _get_style_name()
    {
        return 'default';
    }
    
    function _get_res_name()
    {
        static $result = null;
        
        if($result === null){
            $arr = array('res' => 'default', 'lib' => 'javascript');
            $resFile = ROOT_PATH . "/includes/res.inc.php";
            $result = file_exists($resFile) ? require $resFile : $arr;
        }
        
        return $result;
        
    }

    /**
     *    当前位置
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function _curlocal($arr)
    {
        $curlocal = array(array(
                'text' => Lang::get('index'),
                'url' => SITE_URL . '/index.php',
        ));
        if (is_array($arr))
        {
            $curlocal = array_merge($curlocal, $arr);
        }
        else
        {
            $args = func_get_args();
            if (!empty($args))
            {
                $len = count($args);
                for ($i = 0; $i < $len; $i += 2)
                {
                    $curlocal[] = array(
                        'text' => $args[$i],
                        'url' => $args[$i + 1],
                    );
                }
            }
        }

        $this->assign('_curlocal', $curlocal);
    }

    function _init_visitor()
    {
        $this->visitor = & env('visitor', new UserVisitor());
    }

    /**
     *    热门搜索
     *
     *    @author   yanghj 2014.6.21
     *    @param    none
     *    @return   array
     */
    function _get_hot_keywords()
    {
        $keywords = explode(',', conf::get('hot_search'));
        return $keywords;
    }

}

/**
 *    前台访问者
 *
 *    @author    Garbin
 *    @usage    none
 */
class UserVisitor extends BaseVisitor
{

    var $_info_key = 'user_info';

    /**
     *    退出登录
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function logout()
    {
        /* 将购物车中的相关项的session_id置为空 */
        $mod_cart = & m('cart');
        $mod_cart->edit("user_id = '" . $this->get('user_id') . "'", array(
            'session_id' => '',
        ));

        /* 退出登录 */
        parent::logout();
    }

}

/**
 *    商城控制器基类
 *
 *    @author    Garbin
 *    @usage    none
 */
class MallbaseApp extends FrontendApp
{

    function _run_action()
    {
        /* 只有登录的用户才可访问 */
        if (!$this->visitor->has_login && in_array(APP, array('apply')))
        {
            header('Location: index.php?app=member&act=login&ret_url=' . rawurlencode($_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING']));

            return;
        }

        parent::_run_action();
    }

    function _config_view()
    {
        parent::_config_view();

        $template_name = $this->_get_template_name();
//        $style_name = $this->_get_style_name();
        $res = $this->_get_res_name();
        
        $this->_view->template_dir = ROOT_PATH . "/themes/mall/{$template_name}";
        $this->_view->compile_dir = ROOT_PATH . "/temp/compiled/mall/{$template_name}";
        $this->_view->res_base = SITE_URL . "/themes/mall/{$template_name}/styles/{$res['res']}";
        $this->_view->lib_base      = SITE_URL . "/includes/libraries/{$res['lib']}";
    }

    /* 取得支付方式实例 */

    function _get_payment($code, $payment_info)
    {
        include_once(ROOT_PATH . '/includes/payment.base.php');
        include(ROOT_PATH . '/includes/payments/' . $code . '/' . $code . '.payment.php');
        $class_name = ucfirst($code) . 'Payment';

        return new $class_name($payment_info);
    }

    /**
     *   获取当前所使用的模板名称
     *
     *    @author    Garbin
     *    @return    string
     */
    function _get_template_name()
    {
        $template_name = Conf::get('template_name');
        if (!$template_name)
        {
            $template_name = 'default';
        }

        return $template_name;
    }

    /**
     *    获取当前模板中所使用的风格名称
     *
     *    @author    Garbin
     *    @return    string
     */
    function _get_style_name()
    {
        $style_name = Conf::get('style_name');
        if (!$style_name)
        {
            $style_name = 'default';
        }

        return $style_name;
    }
    
}

/**
 *    购物流程子系统基础类
 *
 *    @author    Garbin
 *    @usage    none
 */
class ShoppingbaseApp extends MallbaseApp
{

    function _run_action()
    {
        /* 只有登录的用户才可访问 */
        if (!$this->visitor->has_login && !in_array(ACT, array('login', 'register', 'check_user')))
        {
            if (!IS_AJAX)
            {
               header('Location:index.php?app=member&act=login&ret_url=' . rawurlencode($_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING']));
               // header('Location:index.php?app=member&act=login&ret_url=' . rawurlencode($_SERVER['PHP_SELF'] . '?' . 'app=cart'));

                return;
            }
            else
            {
                $this->json_error('login_please');
                return;
            }
        }

        parent::_run_action();
    }

}

/**
 *    用户中心子系统基础类
 *
 *    @author    Garbin
 *    @usage    none
 */
class MemberbaseApp extends MallbaseApp
{

    function _run_action()
    {
        /* 只有登录的用户才可访问 */
        if (!$this->visitor->has_login && !in_array(ACT, array('login', 'register', 'check_user', 'Ajaxlogin', 'Ajax_islogin')))
        {
            if (!IS_AJAX)
            {
                header('Location:index.php?app=member&act=login&ret_url=' . rawurlencode($_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING']));

                return;
            }
            else
            {
                $this->json_error('login_please');
                return;
            }
        }

        parent::_run_action();
    }

    /**
     *    当前选中的菜单项
     *
     *    @author    Garbin
     *    @param     string $item
     *    @return    void
     */
    function _curitem($item)
    {
        if ($_GET['from'] == 'seller')
        {
            if (!$this->visitor->get('store_id'))
            {
                header("Location:index.php?app=apply");
                exit;
            }
        }
        $this->assign('has_store', $this->visitor->get('store_id'));
        //$this->assign('_member_menu', $this->_get_member_menu());
        $this->assign('_seller_member_menu', $this->_get_seller_member_menu());
        $this->assign('_buyer_member_menu', $this->_get_buyer_member_menu());
        $this->assign('_curitem', $item);
    }

    /**
     *    当前选中的子菜单
     *
     *    @author    Garbin
     *    @param     string $item
     *    @return    void
     */
    function _curmenu($item)
    {
        $_member_submenu = $this->_get_member_submenu();
        foreach ($_member_submenu as $key => $value)
        {
            $_member_submenu[$key]['text'] = $value['text'] ? $value['text'] : Lang::get($value['name']);
        }
        $this->assign('_member_submenu', $_member_submenu);
        $this->assign('_curmenu', $item);
    }

    /**
     *    获取子菜单列表
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function _get_member_submenu()
    {
        return array();
    }

    /**
     *    获取用户中心全局菜单列表
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
    function _get_member_menu()
    {
        $menu = array();

        /* 我的ECMall */
        $menu['my_ecmall'] = array(
            'name' => 'my_ecmall',
            'text' => Lang::get('my_ecmall'),
            'submenu' => array(
                'overview' => array(
                    'text' => Lang::get('overview'),
                    'url' => 'index.php?app=member',
                    'name' => 'overview',
                    'icon' => 'ico1',
                ),
                'my_profile' => array(
                    'text' => Lang::get('my_profile'),
                    'url' => 'index.php?app=member&act=profile',
                    'name' => 'my_profile',
                    'icon' => 'ico2',
                ),
                'message' => array(
                    'text' => Lang::get('message'),
                    'url' => 'index.php?app=message&act=newpm',
                    'name' => 'message',
                    'icon' => 'ico3',
                ),
                'friend' => array(
                    'text' => Lang::get('friend'),
                    'url' => 'index.php?app=friend',
                    'name' => 'friend',
                    'icon' => 'ico4',
                ),
            /*
              'my_credit'  => array(
              'text'  => Lang::get('my_credit'),
              'url'   => 'index.php?app=member&act=credit',
              'name'  => 'my_credit',
              ), */
            ),
        );

        /* 我是买家 */
        $menu['im_buyer'] = array(
            'name' => 'im_buyer',
            'text' => Lang::get('im_buyer'),
            'submenu' => array(
                'my_order' => array(
                    'text' => Lang::get('my_order'),
                    'url' => 'index.php?app=buyer_order',
                    'name' => 'my_order',
                    'icon' => 'ico5',
                ),
                'my_groupbuy' => array(
                    'text' => Lang::get('my_groupbuy'),
                    'url' => 'index.php?app=buyer_groupbuy',
                    'name' => 'my_groupbuy',
                    'icon' => 'ico21',
                ),
                'my_question' => array(
                    'text' => Lang::get('my_question'),
                    'url' => 'index.php?app=my_question',
                    'name' => 'my_question',
                    'icon' => 'ico17',
                ),
                'my_favorite' => array(
                    'text' => Lang::get('my_favorite'),
                    'url' => 'index.php?app=my_favorite',
                    'name' => 'my_favorite',
                    'icon' => 'ico6',
                ),
                'my_address' => array(
                    'text' => Lang::get('my_address'),
                    'url' => 'index.php?app=my_address',
                    'name' => 'my_address',
                    'icon' => 'ico7',
                ),
                'my_coupon' => array(
                    'text' => Lang::get('my_coupon'),
                    'url' => 'index.php?app=my_coupon',
                    'name' => 'my_coupon',
                    'icon' => 'ico20',
                ),
            ),
        );

        if (!$this->visitor->get('has_store') && Conf::get('store_allow'))
        {
            /* 没有拥有店铺，且开放申请，则显示申请开店链接 */
            /* $menu['im_seller'] = array(
              'name'  => 'im_seller',
              'text'  => Lang::get('im_seller'),
              'submenu'   => array(),
              );

              $menu['im_seller']['submenu']['overview'] = array(
              'text'  => Lang::get('apply_store'),
              'url'   => 'index.php?app=apply',
              'name'  => 'apply_store',
              ); */
            $menu['overview'] = array(
                'text' => Lang::get('apply_store'),
                'url' => 'index.php?app=apply',
            );
        }
        if ($this->visitor->get('manage_store'))
        {
            /* 指定了要管理的店铺 */
            $menu['im_seller'] = array(
                'name' => 'im_seller',
                'text' => Lang::get('im_seller'),
                'submenu' => array(),
            );
            $menu['im_seller']['submenu']['seller_address'] = array(
                'text' => Lang::get('seller_address'),
                'url' => 'index.php?app=seller_address',
                'name' => 'seller_address',
                'icon' => 'ico7',
            );

            $menu['im_seller']['submenu']['my_goods'] = array(
                'text' => Lang::get('my_goods'),
                'url' => 'index.php?app=my_goods',
                'name' => 'my_goods',
                'icon' => 'ico8',
            );
            $menu['im_seller']['submenu']['groupbuy_manage'] = array(
                'text' => Lang::get('groupbuy_manage'),
                'url' => 'index.php?app=seller_groupbuy',
                'name' => 'groupbuy_manage',
                'icon' => 'ico22',
            );
            $menu['im_seller']['submenu']['my_qa'] = array(
                'text' => Lang::get('my_qa'),
                'url' => 'index.php?app=my_qa',
                'name' => 'my_qa',
                'icon' => 'ico18',
            );
            $menu['im_seller']['submenu']['my_category'] = array(
                'text' => Lang::get('my_category'),
                'url' => 'index.php?app=my_category',
                'name' => 'my_category',
                'icon' => 'ico9',
            );
            $menu['im_seller']['submenu']['order_manage'] = array(
                'text' => Lang::get('order_manage'),
                'url' => 'index.php?app=seller_order',
                'name' => 'order_manage',
                'icon' => 'ico10',
            );
            $menu['im_seller']['submenu']['my_store'] = array(
                'text' => Lang::get('my_store'),
                'url' => 'index.php?app=my_store',
                'name' => 'my_store',
                'icon' => 'ico11',
            );
            $menu['im_seller']['submenu']['my_theme'] = array(
                'text' => Lang::get('my_theme'),
                'url' => 'index.php?app=my_theme',
                'name' => 'my_theme',
                'icon' => 'ico12',
            );
            $menu['im_seller']['submenu']['my_payment'] = array(
                'text' => Lang::get('my_payment'),
                'url' => 'index.php?app=my_payment',
                'name' => 'my_payment',
                'icon' => 'ico13',
            );
            $menu['im_seller']['submenu']['my_shipping'] = array(
                'text' => Lang::get('my_shipping'),
                'url' => 'index.php?app=my_shipping',
                'name' => 'my_shipping',
                'icon' => 'ico14',
            );
            $menu['im_seller']['submenu']['my_navigation'] = array(
                'text' => Lang::get('my_navigation'),
                'url' => 'index.php?app=my_navigation',
                'name' => 'my_navigation',
                'icon' => 'ico15',
            );
            $menu['im_seller']['submenu']['my_partner'] = array(
                'text' => Lang::get('my_partner'),
                'url' => 'index.php?app=my_partner',
                'name' => 'my_partner',
                'icon' => 'ico16',
            );
            $menu['im_seller']['submenu']['coupon'] = array(
                'text' => Lang::get('coupon'),
                'url' => 'index.php?app=coupon',
                'name' => 'coupon',
                'icon' => 'ico19',
            );
        }

        return $menu;
    }

    /**
     *    获取卖家中心菜单列表
     *
     *    @author    yanghj 2014.5.4
     *    @param    none
     *    @return    void
     */
    function _get_seller_member_menu()
    {
        $menu = array();



        if (!$this->visitor->get('has_store') && Conf::get('store_allow'))
        {

            $menu['overview'] = array(
                'text' => Lang::get('apply_store'),
                'url' => 'index.php?app=apply',
            );
        }
        if ($this->visitor->get('manage_store'))
        {
            //卖出的商品            
            $menu['sale_goods'] = array(
                'name' => 'sale_goods',
                'text' => Lang::get('sale_goods'),
                'url' => 'index.php?app=seller_order',
            );
            //评价管理    
            $menu['review'] = array(
                'name' => 'review',
                'text' => Lang::get('review'),
                'url' => 'index.php?app=seller_order&act=evalua',
            );
            //消息提醒
            $menu['notifications'] = array(
                'name' => 'notifications',
                'text' => Lang::get('notifications'),
                'url' => 'index.php?app=my_qa',
            );
            //商品管理
            $menu['my_goods'] = array(
                'name' => 'im_seller',
                'text' => Lang::get('my_goods'),
                'submenu' => array(),
            );
            //发布新商品
            $menu['my_goods']['submenu']['my_goods_add'] = array(
                'text' => Lang::get('my_goods_add'),
                'url' => 'index.php?app=my_goods&act=add',
                'name' => 'my_goods_add',
                'icon' => 'ico1',
            );
            //全部商品
            $menu['my_goods']['submenu']['my_goods_all'] = array(
                'text' => Lang::get('all_goods'),
                'url' => 'index.php?app=my_goods',
                'name' => 'my_goods_all',
                'icon' => 'ico2',
            );
            //出售中
            $menu['my_goods']['submenu']['my_goods_sell'] = array(
                'text' => Lang::get('my_goods_sell'),
                'url' => 'index.php?app=my_goods&character=show',
                'name' => 'my_goods_sell',
                'icon' => 'ico3',
            );
            //待上架
            $menu['my_goods']['submenu']['my_goods_await'] = array(
                'text' => Lang::get('my_goods_await'),
                'url' => 'index.php?app=my_goods&character=hide',
                'name' => 'my_goods_await',
                'icon' => 'ico4',
            );
            //已下架
            $menu['my_goods']['submenu']['my_goods_drops'] = array(
                'text' => Lang::get('my_goods_drops'),
                'url' => 'index.php?app=my_goods&character=closed',
                'name' => 'my_goods_drops',
                'icon' => 'ico5',
            );
            //商品分类管理
            $menu['my_goods']['submenu']['my_category'] = array(
                'text' => Lang::get('my_goods_category'),
                'url' => 'index.php?app=my_category',
                'name' => 'my_category',
                'icon' => 'ico6',
            );
            /* $menu['my_goods']['submenu']['my_goods_optimize'] = array(
              'text'  => '待优化商品',
              'url'   => '#',
              'name'  => 'my_goods_optimize',
              'icon'  => 'ico7',
              ); */
            //店铺管理
            $menu['my_shop'] = array(
                'name' => 'my_shop',
                'text' => Lang::get('my_shop'),
                'submenu' => array(),
            );
            //查看我的店铺
            $menu['my_shop']['submenu']['my_store_check'] = array(
                'text' => Lang::get('my_store_check'),
                'url' => 'index.php?app=store&id=' . $this->visitor->get('store_id'),
                'name' => '',
                'icon' => 'ico7',
                'target' => '_black'
            );
            //店铺设置
            $menu['my_shop']['submenu']['my_store'] = array(
                'text' => Lang::get('my_store'),
                'url' => 'index.php?app=my_store',
                'name' => 'my_store',
                'icon' => 'ico8',
            );
            //物流设置
            $menu['my_shop']['submenu']['my_logistics'] = array(
                'text' => Lang::get('my_logistics'),
                'url' => 'index.php?app=my_shipping',
                'name' => 'my_logistics',
                'icon' => 'ico9',
            );
            //退货/发货地址
            $menu['my_shop']['submenu']['seller_address'] = array(
                'text' => Lang::get('seller_address'),
                'url' => 'index.php?app=seller_address&act=returns',
                'name' => 'seller_address',
                'icon' => 'ico10',
            );
            //客户服务
            $menu['my_service'] = array(
                'name' => 'my_service',
                'text' => Lang::get('my_service'),
                'submenu' => array(),
            );
            //退货/退款管理
            $menu['my_service']['submenu']['my_sales_return'] = array(
                'text' => Lang::get('my_sales_return'),
                'url' => 'index.php?app=seller_returns',
                'name' => 'my_sales_return',
                'icon' => 'ico11',
            );
            //售后管理
            /* $menu['my_service']['submenu']['my_after_sales'] = array(
              'text'  => Lang::get('my_after_sales'),
              'url'   => 'index.php?app=qos_seller&act=complain',
              'name'  => 'my_after_sales',
              'icon'  => 'ico12',
              );
             */
            //营销设置
            $menu['my_marketing'] = array(
                'name' => 'my_marketing',
                'text' => Lang::get('my_marketing'),
                'submenu' => array(),
            );
            //限时促销管理
            $menu['my_marketing']['submenu']['my_promotion'] = array(
                'text' => Lang::get('my_promotion'),
                'url' => 'index.php?app=my_promotion',
                'name' => 'my_promotion',
                'icon' => 'ico11',
            );
              //账户管理
              $menu['my_account'] = array(
              'name'  => 'my_account',
              'text'  => Lang::get('my_account'),
              'submenu'   => array(),
              );
              //安全设置
              $menu['my_account']['submenu']['my_safety'] = array(
              'text'  => Lang::get('my_safety'),
              'url'   => 'index.php?app=account_security&from=seller',
              'name'  => 'my_safety',
              'icon'  => 'ico13',
              );
              /* 
              //基本资料
              $menu['my_account']['submenu']['my_profile'] = array(
              'text'  => Lang::get('my_information'),
              'url'   => 'index.php?app=member&act=profile&from=seller',
              'name'  => 'my_profile',
              'icon'  => 'ico14',
              );
              //资金管理
              $menu['my_capital'] = array(
              'name'  => 'my_capital',
              'text'  => Lang::get('my_capital'),
              'submenu'   => array(),
              );
              //账户信息
              $menu['my_capital']['submenu']['my_account_information'] = array(
              'text'  => Lang::get('my_account_information'),
              'url'   => 'index.php?app=paycenter&act=account_info&from=seller',
              'name'  => 'my_account_information',
              'icon'  => 'ico16',
              );
              //网上充值
              $menu['my_capital']['submenu']['my_recharge'] = array(
              'text'  => Lang::get('my_recharge'),
              'url'   => 'index.php?app=paycenter&act=recharge&from=seller',
              'name'  => 'my_recharge',
              'icon'  => 'ico17',
              );
              //提现
              $menu['my_capital']['submenu']['my_currency'] = array(
              'text'  => Lang::get('my_currency'),
              'url'   => 'index.php?app=paycenter&act=cash&from=seller',
              'name'  => 'my_currency',
              'icon'  => 'ico18',
              );
              //收支明细
              $menu['my_capital']['submenu']['my_detail'] = array(
              'text'  => Lang::get('my_detail'),
              'url'   => 'index.php?app=paycenter&act=my_account&from=seller',
              'name'  => 'my_detail',
              'icon'  => 'ico19',
              );
             */

            //商户结算
            $menu['my_clearing'] = array(
                'name'  => 'my_clearing',
                'text'  => Lang::get('my_clearing'),
                'submenu'   => array(),
            );
            //可结算的订单
            $menu['my_clearing']['submenu']['seller_clearing'] = array(
                'text'  => Lang::get('seller_clearing'),
                'url'   => 'index.php?app=my_clearing',
                'name'  => 'seller_clearing',
                'icon'  => 'ico1',
            );
            //已结算的订单记录
            $menu['my_clearing']['submenu']['seller_clearing_record'] = array(
                'text'  => Lang::get('seller_clearing_record'),
                'url'   => 'index.php?app=my_clearing&act=record',
                'name'  => 'seller_clearing_record',
                'icon'  => 'ico1',
            );
        }

        return $menu;
    }

    /**
     *    获取买家中心菜单列表
     *
     *    @author    yanghj 2014.5.4
     *    @param    none
     *    @return    void
     */
    function _get_buyer_member_menu()
    {
        $menu = array();

        //买到的商品            
        $menu['buyer_goods'] = array(
            'name' => 'buyer_goods',
            'text' => Lang::get('buyer_goods'),
            'url' => 'index.php?app=buyer_order',
        );
        //我的进货车  
        $menu['my_shopping_cat'] = array(
            'name' => 'my_shopping_cat',
            'text' => Lang::get('my_shopping_cat'),
            'url' => 'index.php?app=cart',
            'target' => '_black'
        );
        //我的收藏  
        $menu['my_favorite'] = array(
            'name' => 'my_favorite',
            'text' => Lang::get('my_favorite'),
            'url' => 'index.php?app=my_favorite',
        );
        //评价管理    
        $menu['review'] = array(
            'name' => 'review',
            'text' => Lang::get('review'),
            'url' => 'index.php?app=buyer_order&act=evalua',
        );
        //消息提醒
        $menu['notifications'] = array(
            'name' => 'notifications',
            'text' => Lang::get('notifications'),
            'url' => 'index.php?app=my_question',
        );
        //客户服务
        $menu['my_service'] = array(
            'name' => 'my_service',
            'text' => Lang::get('my_service'),
            'submenu' => array(),
        );
        //退货/退款管理
        $menu['my_service']['submenu']['my_sales_return'] = array(
            'text' => Lang::get('my_sales_return'),
            'url' => 'index.php?app=buyer_returns',
            'name' => 'my_sales_return',
            'icon' => 'ico11',
        );
        //售后管理
        /* $menu['my_service']['submenu']['my_after_sales'] = array(
          'text'  => Lang::get('my_after_sales'),
          'url'   => 'index.php?app=qos_buyer',
          'name'  => 'my_after_sales',
          'icon'  => 'ico12',
          ); */
        //账户管理
        $menu['my_account'] = array(
            'name' => 'my_account',
            'text' => Lang::get('my_account'),
            'submenu' => array(),
        );
        //安全设置
        $menu['my_account']['submenu']['my_safety'] = array(
            'text' => Lang::get('my_safety'),
            'url' => 'index.php?app=account_security&from=buyer',
            'name' => 'my_safety',
            'icon' => 'ico13',
        );
        //基本资料
        $menu['my_account']['submenu']['my_profile'] = array(
            'text' => Lang::get('my_information'),
            'url' => 'index.php?app=member&act=profile&from=buyer',
            'name' => 'my_profile',
            'icon' => 'ico14',
        );
        //收货地址
        $menu['my_account']['submenu']['my_address'] = array(
            'text' => Lang::get('my_receiving_address'),
            'url' => 'index.php?app=my_address',
            'name' => 'my_address',
            'icon' => 'ico15',
        );
        //资金管理
        $menu['my_capital'] = array(
            'name' => 'my_capital',
            'text' => Lang::get('my_capital'),
            'submenu' => array(),
        );
        //账户信息
        $menu['my_capital']['submenu']['my_account_information'] = array(
            'text' => Lang::get('my_account_information'),
            'url' => 'index.php?app=paycenter&act=account_info&from=buyer',
            'name' => 'my_account_information',
            'icon' => 'ico16',
        );
        //网上充值
        /* $menu['my_capital']['submenu']['my_recharge'] = array(
          'text'  => Lang::get('my_recharge'),
          'url'   => 'index.php?app=paycenter&act=recharge&from=buyer',
          'name'  => 'my_recharge',
          'icon'  => 'ico17',
          ); */
        //兑换礼品卡
        $menu['my_capital']['submenu']['my_recharge_card'] = array(
            'text' => Lang::get('my_recharge_card'),
            'url' => 'index.php?app=paycenter&act=recharge_card&from=buyer',
            'name' => 'my_recharge_card',
            'icon' => 'ico17',
        );
        //提现
        /* $menu['my_capital']['submenu']['my_currency'] = array(
          'text'  => Lang::get('my_currency'),
          'url'   => 'index.php?app=paycenter&act=cash&from=buyer',
          'name'  => 'my_currency',
          'icon'  => 'ico18',
          ); */
        //收支明细
        $menu['my_capital']['submenu']['my_detail'] = array(
            'text' => Lang::get('my_detail'),
            'url' => 'index.php?app=paycenter&act=my_account&from=buyer',
            'name' => 'my_detail',
            'icon' => 'ico19',
        );

        return $menu;
    }

}

/**
 *    店铺管理子系统基础类
 *
 *    @author    Garbin
 *    @usage    none
 */
class StoreadminbaseApp extends MemberbaseApp
{

    function _run_action()
    {
        /* 只有登录的用户才可访问 */
        if (!$this->visitor->has_login && !in_array(ACT, array('login', 'register', 'check_user')))
        {
            if (!IS_AJAX)
            {
                header('Location:index.php?app=member&act=login&ret_url=' . rawurlencode($_SERVER['PHP_SELF'] . '?' . $_SERVER['QUERY_STRING']));

                return;
            }
            else
            {
                $this->json_error('login_please');
                return;
            }
        }
        $referer = $_SERVER['HTTP_REFERER'];
        if (strpos($referer, 'act=login') === false)
        {
            $ret_url = $_SERVER['HTTP_REFERER'];
            $ret_text = 'go_back';
        }
        else
        {
            $ret_url = SITE_URL . '/index.php';
            $ret_text = 'back_index';
        }

        /* 检查是否是店铺管理员 */
        if (!$this->visitor->get('manage_store'))
        {
            /* 您不是店铺管理员 */
            $this->show_warning(
                'not_storeadmin', 'apply_now', 'index.php?app=apply', $ret_text, $ret_url
            );

            return;
        }

        /* 检查是否被授权 */
        $privileges = $this->_get_privileges();
        if (!$this->visitor->i_can('do_action', $privileges))
        {
            if (strpos(strtolower(ACT), "ajax") !== false)
                $this->json_error('no_permission');
            else
                $this->show_warning('no_permission', $ret_text, $ret_url);

            return;
        }

        /* 检查店铺开启状态 */
        $state = $this->visitor->get('state');
        if ($state == 0)
        {
            $this->show_warning('apply_not_agree', $ret_text, $ret_url);

            return;
        }
        elseif ($state == 2)
        {
            $this->show_warning('store_is_closed', $ret_text, $ret_url);

            return;
        }

        /* 检查附加功能 */
        if (!$this->_check_add_functions())
        {
            $this->show_warning('not_support_function', $ret_text, $ret_url);
            return;
        }

        parent::_run_action();
    }

    function _get_privileges()
    {
        $store_id = $this->visitor->get('manage_store');
        $privs = $this->visitor->get('s');

        if (empty($privs))
        {
            return '';
        }

        foreach ($privs as $key => $admin_store)
        {
            if ($admin_store['store_id'] == $store_id)
            {
                return $admin_store['privs'];
            }
        }
    }

    /* 获取当前店铺所使用的主题 */

    function _get_theme()
    {
        $model_store = & m('store');
        $store_info = $model_store->get($this->visitor->get('manage_store'));
        $theme = !empty($store_info['theme']) ? $store_info['theme'] : 'default|default';
        list($curr_template_name, $curr_style_name) = explode('|', $theme);
        return array(
            'template_name' => $curr_template_name,
            'style_name' => $curr_style_name,
        );
    }

    function _check_add_functions()
    {
        $apps_functions = array(// app与function对应关系
            'seller_groupbuy' => 'groupbuy',
            'coupon' => 'coupon',
        );
        if (isset($apps_functions[APP]))
        {
            $store_mod = & m('store');
            $settings = $store_mod->get_settings($this->_store_id);
            $add_functions = isset($settings['functions']) ? $settings['functions'] : ''; // 附加功能
            if (!in_array($apps_functions[APP], explode(',', $add_functions)))
            {
                return false;
            }
        }
        return true;
    }

}

/**
 *    店铺控制器基础类
 *
 *    @author    Garbin
 *    @usage    none
 */
class StorebaseApp extends FrontendApp
{

    var $_store_id;

    /**
     * 设置店铺id
     *
     * @param int $store_id
     */
    function set_store($store_id)
    {
        $this->_store_id = intval($store_id);

        /* 有了store id后对视图进行二次配置 */
        $this->_init_view();
        $this->_config_view();
    }

    function _config_view()
    {
        parent::_config_view();
        $template_name = $this->_get_template_name();
//        $style_name = $this->_get_style_name();
        $res = $this->_get_res_name();

        $this->_view->template_dir = ROOT_PATH . "/themes/store/{$template_name}";
        $this->_view->compile_dir = ROOT_PATH . "/temp/compiled/store/{$template_name}";
        $this->_view->res_base = SITE_URL . "/themes/store/{$template_name}/styles/{$res['res']}";
        $this->_view->lib_base      = SITE_URL . "/includes/libraries/{$res['lib']}";
    }

    /**
     * 取得店铺信息
     */
    function get_store_data()
    {
        $cache_server = & cache_server();
        $key = 'function_get_store_data_' . $this->_store_id;
        $store = $cache_server->get($key);
        if ($store === false)
        {
            $store = $this->_get_store_info();
            if (empty($store))
            {
                $this->show_warning('the_store_not_exist');
                exit;
            }
            if ($store['state'] == 2)
            {
                $this->show_warning('the_store_is_closed');
                exit;
            }
            $step = intval(Conf::get('upgrade_required'));
            $step < 1 && $step = 5;
            $store_mod = & m('store');
            $store['credit_image'] = $this->_view->res_base . '/images/' . $store_mod->compute_credit($store['credit_value'], $step);

            empty($store['store_logo']) && $store['store_logo'] = Conf::get('default_store_logo');
            $store['store_owner'] = $this->_get_store_owner();
            $store['store_navs'] = $this->_get_store_nav();
            $goods_mod = & m('goods');
            $store['goods_count'] = $goods_mod->get_count_of_store($this->_store_id);
            $store['store_gcates'] = $this->_get_store_gcategory();
            $store['sgrade'] = $this->_get_store_grade('grade_name');
            $functions = $this->_get_store_grade('functions');
            $store['functions'] = array();
            if ($functions)
            {
                $functions = explode(',', $functions);
                foreach ($functions as $k => $v)
                {
                    $store['functions'][$v] = $v;
                }
            }
            $cache_server->set($key, $store, 1800);
        }

        return $store;
    }

    /* 取得店铺信息 */

    function _get_store_info()
    {
        if (!$this->_store_id)
        {
            /* 未设置前返回空 */
            return array();
        }
        static $store_info = null;
        if ($store_info === null)
        {
            $store_mod = & m('store');
            $store_info = $store_mod->get_info($this->_store_id);
        }

        return $store_info;
    }

    /* 取得店主信息 */

    function _get_store_owner()
    {
        $user_mod = & m('member');
        $user = $user_mod->get($this->_store_id);

        return $user;
    }

    /* 取得店铺导航 */

    function _get_store_nav()
    {
        $article_mod = & m('article');
        return $article_mod->find(array(
                'conditions' => "store_id = '{$this->_store_id}' AND cate_id = '" . STORE_NAV . "' AND if_show = 1",
                'order' => 'sort_order',
                'fields' => 'title',
        ));
    }

    /*  取的店铺等级   */

    function _get_store_grade($field)
    {
        $store_info = $store_info = $this->_get_store_info();
        $sgrade_mod = & m('sgrade');
        $result = $sgrade_mod->get_info($store_info['sgrade']);
        return $result[$field];
    }

    /* 取得店铺分类 */

    function _get_store_gcategory()
    {
        $gcategory_mod = & bm('gcategory', array('_store_id' => $this->_store_id));
        $gcategories = $gcategory_mod->get_list(-1, true);
        import('tree.lib');
        $tree = new Tree();
        $tree->setTree($gcategories, 'cate_id', 'parent_id', 'cate_name');
        return $tree->getArrayList(0);
    }

    /**
     *    获取当前店铺所设定的模板名称
     *
     *    @author    Garbin
     *    @return    string
     */
    function _get_template_name()
    {
        $store_info = $this->_get_store_info();
        $theme = !empty($store_info['theme']) ? $store_info['theme'] : 'default|default';
        list($template_name, $style_name) = explode('|', $theme);

        return $template_name;
    }

    /**
     *    获取当前店铺所设定的风格名称
     *
     *    @author    Garbin
     *    @return    string
     */
    function _get_style_name()
    {
        $store_info = $this->_get_store_info();
        $theme = !empty($store_info['theme']) ? $store_info['theme'] : 'default|default';
        list($template_name, $style_name) = explode('|', $theme);

        return $style_name;
    }

}

/* 实现消息基础类接口 */

class MessageBase extends MallbaseApp
{
    
}

;

/* 实现模块基础类接口 */

class BaseModule extends FrontendApp
{
    
}

;

/* 消息处理器 */
require(ROOT_PATH . '/eccore/controller/message.base.php');
?>
